package com.zwh.common.easyexcel;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;

/**
 * easyexcel注解导出工具类
 * @author zwh
 * @date 2021/3/4 16:44
 **/
public class EasyExcelWriteExportUtils {

    /**
     * 注解导出数据到流
     * @param exportList
     * @param outputStream
     * @param isCloseExcel
     * @return
     */
    public static ExcelWriter exportToOutputStream(List exportList, String sheetName,
                                               Class clazz,
                                               OutputStream outputStream,
                                               boolean isCloseExcel) {
        ExcelWriter excelWriter = null;
        try {
            // 头的策略
            WriteCellStyle headWriteCellStyle = EasyExcelWriteExportUtils.buildHeadCellStyle();
            HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle,
                    new ArrayList<WriteCellStyle>());

            excelWriter = EasyExcelWriteExportUtils.getExcelWriter(clazz,
                    Arrays.asList(horizontalCellStyleStrategy),
                    outputStream);

            WriteSheet writeSheet = EasyExcel.writerSheet(sheetName).build();
            excelWriter.write(exportList, writeSheet);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(isCloseExcel){
                // 别忘记关闭流
                if (excelWriter != null) {
                    excelWriter.finish();
                }
            }
        }
        if (isCloseExcel) {
            return null;
        } else {
            return excelWriter;
        }
    }

    /**
     * 注解导出工具类
     * @param exportList
     * @param outFileName
     * @param response
     * @param isCloseExcel
     * @return
     */
    public static ExcelWriter exportToResponse(List exportList, String outFileName,
                                                  String sheetName,
                                                  Class clazz,
                                                  HttpServletResponse response,
                                                  boolean isCloseExcel) {
        ExcelWriter excelWriter = null;
        try {
            // 头的策略
            WriteCellStyle headWriteCellStyle = EasyExcelWriteExportUtils.buildHeadCellStyle();
            HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle,
                    new ArrayList<WriteCellStyle>());

            excelWriter = EasyExcelWriteExportUtils.getExcelWriter(outFileName,
                    clazz,
                    Arrays.asList(horizontalCellStyleStrategy),
                    response);

            WriteSheet writeSheet = EasyExcel.writerSheet(sheetName).build();
            excelWriter.write(exportList, writeSheet);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(isCloseExcel){
                // 别忘记关闭流
                if (excelWriter != null) {
                    excelWriter.finish();
                }
            }
        }
        if (isCloseExcel) {
            return null;
        } else {
            return excelWriter;
        }
    }

    /**
     * 根据输出文件名获取excelWriter类
     *
     * @param outFileName
     * @param response
     */
    public static ExcelWriter getExcelWriter(String outFileName, Class clazz, List<WriteHandler> writeHandlerList, HttpServletResponse response) throws IOException {
        response.reset();
        response.setContentType("application/octet-stream; charset=utf-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + outFileName);
        return getExcelWriter(clazz, writeHandlerList, response.getOutputStream());
    }

    public static ExcelWriter getExcelWriter(Class clazz, List<WriteHandler> writeHandlerList, OutputStream out){
        ExcelWriter excelWriter = null;
        //这里指定需要表头，因为model通常包含表信头息
        if (writeHandlerList != null && !writeHandlerList.isEmpty()) {
            ExcelWriterBuilder excelWriterBuilder = EasyExcelFactory.write(out, clazz);
            for (WriteHandler writeHandler : writeHandlerList) {
                excelWriterBuilder.registerWriteHandler(writeHandler);
            }
            excelWriter = excelWriterBuilder.build();
        } else {
            excelWriter = EasyExcelFactory.write(out, clazz).build();
        }

        return excelWriter;
    }

    /**
     * @param workbook
     * @return
     */
    public static CellStyle buildDefaultCellStyle(Workbook workbook) {
        CellStyle newCellStyle = workbook.createCellStyle();
        newCellStyle.setWrapText(true);
        newCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        newCellStyle.setAlignment(HorizontalAlignment.CENTER);
        newCellStyle.setLocked(true);
        newCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        newCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        newCellStyle.setBorderTop(BorderStyle.THIN);
        newCellStyle.setBorderBottom(BorderStyle.THIN);
        newCellStyle.setBorderLeft(BorderStyle.THIN);
        newCellStyle.setBorderRight(BorderStyle.THIN);
        return newCellStyle;
    }

    /**
     * Build head cell style
     *
     * @return
     */
    public static WriteCellStyle buildHeadCellStyle() {
//        CellStyle headCellStyle = StyleUtil.buildHeadCellStyle(workbook, null);
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        headWriteCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontName("宋体");
        headWriteFont.setFontHeightInPoints((short)12);
        headWriteFont.setBold(true);
        headWriteCellStyle.setWriteFont(headWriteFont);
        //自动换行
        headWriteCellStyle.setWrapped(false);
        return headWriteCellStyle;
    }
}
